package com.xhwl.data.event;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.starter.config.IConfig;
import com.xhwl.common.pojo.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 19:33 2021/6/17
 */
public class SpaceDeleteListener implements ApplicationListener<SpaceDeleteEvent> {


    private static final Logger log = LoggerFactory.getLogger(SpaceDeleteListener.class);

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @Autowired
    private IConfig config;

    private static final String CONFIG_CODE = "SPACE_MESSAGE_DELETE";

    @Async
    @Override
    public void onApplicationEvent(SpaceDeleteEvent spaceDeleteEvent) {

        Config projectConfig = config.getProject(CONFIG_CODE, spaceDeleteEvent.getProjectId());
        if(null == projectConfig){
            return ;
        }
        String topic = projectConfig.getValue().toString();
        log.info("收到消息 {} 准备推送至队列 {}", JSONObject.toJSONString(spaceDeleteEvent), topic);
        String massage = JSONObject.toJSONString(spaceDeleteEvent);
        ListenableFuture<SendResult<String, Object>> spaceDeleteResult = kafkaTemplate.send(topic, spaceDeleteEvent.getSpace().toString());
        spaceDeleteResult.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onSuccess(SendResult<String, Object> result) {
                log.info("主题 = {}， 空间删除推送成功 = {}",topic, massage);
            }
            @Override
            public void onFailure(Throwable ex) {
                log.info("主题 = {}， 空间删除推送失败 = {}",topic, massage);
            }
        });
    }
}
